<template>
  <el-dialog
    title="重置密码"
    :visible.sync="resetPassDialogVisible"
    width="30%"
    @close="handleClose"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="新密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { resetUserPassword } from '@/api/user/users'

export default {
  name: 'ResetPwdForm',
  props: {
    resetPassDialogVisible: {
      type: Boolean,
      required: true
    },
    curId: {
      type: [Number, String],
      required: true
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const formRef = ref(null)
    const form = ref({
      password: '',
      confirmPassword: ''
    })

    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (form.value.confirmPassword !== '') {
          formRef.value.validateField('confirmPassword')
        }
        callback()
      }
    }

    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== form.value.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    const rules = {
      password: [
        { required: true, validator: validatePass, trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validatePass2, trigger: 'blur' }
      ]
    }

    const handleClose = () => {
      emit('close')
      form.value.password = ''
      form.value.confirmPassword = ''
      formRef.value?.resetFields()
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        await resetUserPassword(props.curId, form.value.password)
        ElMessage.success('密码重置成功')
        handleClose()
      } catch (error) {
        ElMessage.error('密码重置失败：' + error.message)
      }
    }

    return {
      formRef,
      form,
      rules,
      handleClose,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>